package com.whalehearing.tingyou.common.exception;

import com.whalehearing.tingyou.common.enums.BizCodeEnum;
import com.whalehearing.tingyou.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.whalehearing.tingyou.*.controller")
public class GlobalExceptionControllerAdvice {

    @ExceptionHandler(value=MethodArgumentNotValidException.class)
    public Result handleValidExcepton(MethodArgumentNotValidException e){
      log.error("数据检验出现异常，异常类型{},异常信息:{}",e.getClass(),e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
            Map<String,Object> map=new HashMap<>();
            bindingResult.getFieldErrors().forEach(item ->{
                String field = item.getField();
                String defaultMessage = item.getDefaultMessage();
                map.put(field,defaultMessage);
            });
            return Result.error(BizCodeEnum.VALID_EXCEPTION.getCode(),BizCodeEnum.VALID_EXCEPTION.getMessage()).put("data",map);
   }

    @ExceptionHandler(value=Throwable.class)
    public Result handleUnknowExcepton(Throwable throwable){
        log.error("未知异常{}",throwable);
        return Result.error(BizCodeEnum.UNKNOW_EXCEPTION.getCode(),BizCodeEnum.UNKNOW_EXCEPTION.getMessage());
    }
}
